---
import { Code } from "astro/components";
import Copy from "./Copy.astro";

export interface Badge {
  label: 'Tiny' | 'Small' | 'Medium' | 'Large';
  shortLabel: 'XS' | 'S' | 'M' | 'L';
  slug: 'tiny' | 'small' | 'medium' | 'large';
  width: number;
  height: number;
}

interface Props {
  aspectRatio: number;
  alt: string;
  link: string;
  getImagePath: (badge: Badge) => string;
}

const { aspectRatio, alt, link, getImagePath } = Astro.props as Props;

const heights = { tiny: 20, small: 32, medium: 40, large: 48 } as const;
const heightsKeys = Object.keys(heights) as Array<keyof typeof heights>;

const badgeSizes: Badge[] = heightsKeys.map((slug) => ({
  slug,
  label: (slug[0]!.toUpperCase() + slug.slice(1)) as Badge['label'],
  shortLabel: (slug === 'tiny' ? 'XS' : slug[0]!.toUpperCase()) as Badge['shortLabel'],
  width: heights[slug] * aspectRatio,
  height: heights[slug],
}));

const mdSnippet = (badge: Badge) =>
  `[![${alt}](${Astro.site}${getImagePath(badge)})](${link})`;
const htmlSnippet = (badge: Badge) => `<a href="${link}">`
  +`<img src="${Astro.site}${getImagePath(badge)}" alt="${alt}" width="${badge.width}" height="${badge.height}">`
  +`</a>`;
---

<starlight-tabs class="contents">
  <!-- tabs -->
  <ul role="tablist" class="sm:self-start border border-neutral-300 rounded-full flex text-xs sm:text-sm text-center">
    {badgeSizes.map(({ label, shortLabel, slug }, idx) => (
      <li role="presentation" class="grow flex">
        <a role="tab" class="w-full px-3 py-2 sm:px-12 sm:py-2.5 aria-selected:text-white aria-selected:bg-blue-purple-gradient rounded-full" href={`#${slug}`} aria-selected={idx === 0 ? 'true': 'false'} tabindex={idx !== 0 ? -1 : 0}>
          <span class="xs:hidden">{shortLabel}</span>
          <span class="hidden xs:inline">{label}</span>
        </a>
      </li>
    ))}
  </ul>
  {badgeSizes.map((badge, idx) => (
    <!-- panel -->
  <section role="tabpanel" hidden={idx !== 0} class="flex-col gap-4 sm:gap-8 [&:not([hidden])]:flex">
    <h3 class="sr-only" id={badge.slug}>{badge.label}</h3>
    <!-- preview well -->
    <div
      class="relative text-center pt-28 pb-4 rounded-lg border border-neutral-500 bg-neutral-600"
    >
      <div class="absolute inset-0 grid place-content-center">
        <img class="shadow-md" src={`/${getImagePath(badge)}`} width={badge.width} height={badge.height} alt={alt} />
      </div>
      <p class="font-mono text-xs">Badge preview — {badge.width}×{badge.height}</p>
    </div>
    <!-- code snippets to copy/paste -->
    <div class="grid grid-cols-1 sm:grid-cols-2 gap-8">
      <div class="flex flex-col gap-4 [&>:last-child]:grow">
        <div class="flex items-baseline justify-between">
          <h4 class="heading-5 text-white">Markdown</h4>
          <Copy text={mdSnippet(badge)} />
        </div>
        <Code code={mdSnippet(badge)} lang="md" />
      </div>
      <div class="flex flex-col gap-4">
        <div class="flex items-baseline justify-between">
          <h4 class="heading-5 text-white">HTML</h4>
          <Copy text={htmlSnippet(badge)} />
        </div>
        <Code code={htmlSnippet(badge)} lang="html" />
      </div>
    </div>
  </section>
  ))}
</starlight-tabs>

<script>
	class StarlightTabs extends HTMLElement {
		tabs: HTMLAnchorElement[];
		panels: HTMLElement[];

		constructor() {
			super();
			const tablist = this.querySelector<HTMLUListElement>('[role="tablist"]')!;
			this.tabs = [...tablist.querySelectorAll<HTMLAnchorElement>('[role="tab"]')];
			this.panels = [...this.querySelectorAll<HTMLElement>(':scope > [role="tabpanel"]')];

        console.log(this.panels);

			this.tabs.forEach((tab, i) => {
				// Handle clicks for mouse users
				tab.addEventListener('click', (e) => {
					e.preventDefault();
					const currentTab = tablist.querySelector('[aria-selected]');
					if (e.currentTarget !== currentTab) {
						this.switchTab(e.currentTarget as HTMLAnchorElement, i);
					}
				});

				// Handle keyboard input
				tab.addEventListener('keydown', (e) => {
					const index = this.tabs.indexOf(e.currentTarget as any);
					// Work out which key the user is pressing and
					// Calculate the new tab's index where appropriate
					const nextIndex =
						e.key === 'ArrowLeft'
							? index - 1
							: e.key === 'ArrowRight'
							? index + 1
							: e.key === 'Home'
							? 0
							: e.key === 'End'
							? this.tabs.length - 1
							: null;
					if (nextIndex === null) return;
					if (this.tabs[nextIndex]) {
						e.preventDefault();
						this.switchTab(this.tabs[nextIndex], nextIndex);
					}
				});
			});
		}

		switchTab(newTab: HTMLAnchorElement | null | undefined, index: number) {
			if (!newTab) return;

			// Mark all tabs as unselected and hide all tab panels.
			this.tabs.forEach((tab) => {
				tab.removeAttribute('aria-selected');
				tab.setAttribute('tabindex', '-1');
			});
			this.panels.forEach((oldPanel) => {
				oldPanel.hidden = true;
			});

			// Show new panel and mark new tab as selected.
			const newPanel = this.panels[index];
			if (newPanel) newPanel.hidden = false;
			// Restore active tab to the default tab order.
			newTab.removeAttribute('tabindex');
			newTab.setAttribute('aria-selected', 'true');
			newTab.focus();
		}
	}

	customElements.define('starlight-tabs', StarlightTabs);
</script>